package cn.fanyamin.web.struts;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Enumeration;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.fanyamin.business.UserService;
import cn.fanyamin.domain.User;
import cn.fanyamin.util.http.HttpUtil;


public class ApiAction extends BaseAction {
    private static Log logger = LogFactory.getLog(ApiAction.class);
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        ActionForward af = null;
        if (isCancelled(request)) {
            af = cancelled(mapping, form, request, response);
        }
        String cmd = request.getParameter("cmd");
        if(StringUtils.isBlank(cmd)) {
            writeResponse(response);
            return af;
        }
        Method method = null;
        try {
            method = this.getMethod(cmd);
        }  catch (NoSuchMethodException e) { 
            logger.error("Not support this command: " + cmd, e);
            HttpUtil.writeResponse(404, "text/xml", "Not support this command: " + cmd, response);
            return af;
        }
        Object args[] = {mapping, form, request, response };
        af = (ActionForward) method.invoke(this, args);
        return af;
    }
    
    
    public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        ActionForward af = null;
        if (isCancelled(request)) {
            af = cancelled(mapping, form, request, response);
        }
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        UserService userService = this.getWebApp().getUserService(); 
        User user = userService.getUser(userName,password);
        if(user == null) {
            //login failed
        }
        
        writeResponse(response);
        
        return af;
    }


    private void writeResponse(HttpServletResponse response) throws IOException {
        response.setContentType("text/xml");
        response.setStatus(HttpServletResponse.SC_OK);
        File file = new File("./etc/pim_api_resp.xml");
        String strResp =FileUtils.readFileToString(file);
        response.getWriter().println(strResp);
    }
    
    public ActionForward debug(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	ActionForward af = null;
        if (isCancelled(request)) {
            af = cancelled(mapping, form, request, response);
        }
        //final StringBuilder htmlOutput = new StringBuilder();
        final StringBuilder debugOutput = new StringBuilder();
          
        debugOutput.append("\n==Cookies==\n");
        final Cookie[] cookies = request.getCookies();
        Cookie cookie;
        if (cookies != null) {
            for (final Cookie cooky : cookies) {
                cookie = cooky;
                debugOutput.append(cookie.getName() + ": " + cookie.getValue() + "\n");
            }
        }
        debugOutput.append("\n==Request Headers==\n");

        for (final Enumeration headers = request.getHeaderNames(); headers.hasMoreElements();) {
            final String headerName = (String) headers.nextElement();
            final String headerValue = request.getHeader(headerName);
            debugOutput.append(headerName + ": " + headerValue + "\n");
        }

           //Method (GET/POST)

        debugOutput.append("\n==Method==\n");
        debugOutput.append("Method: " + request.getMethod());
        
        //Parameters
        debugOutput.append("\n==Request Parameters==\n");
        for (Enumeration parameters = request.getParameterNames(); parameters.hasMoreElements();) {
            final String parameterName = (String) parameters.nextElement();
            final String parameterValue = request.getParameter(parameterName);
            debugOutput.append(parameterName + ": " + parameterValue + "\n");
        }
 
        //PathInfo
        debugOutput.append("\n==Path Info==\n");
        debugOutput.append("Path Info: " + request.getPathInfo());

        //Path Translated
        debugOutput.append("\n==Path Translated==\n");
        debugOutput.append("Path Translated: " + request.getPathTranslated());

        //Query String
        debugOutput.append("\n==Query String==\n");
        debugOutput.append("Query String: " + request.getQueryString());

        //Request URI
        debugOutput.append("\n==Request URI==\n");
        debugOutput.append("Request URI: " + request.getRequestURI());

        //Servlet Path
        debugOutput.append("\n==Servlet Path==\n");
        debugOutput.append("Servlet Path: " + request.getServletPath());
        
        response.setContentType("text/plain");
        response.setStatus(HttpServletResponse.SC_OK);
        //Output the data to debugger.
        response.getWriter().println(debugOutput.toString());
    
        return af;
    }
    
	public ActionForward status(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        ActionForward af = null;
        if (isCancelled(request)) {
            af = cancelled(mapping, form, request, response);
        }
                
        response.setContentType("text/plain");
        response.setStatus(HttpServletResponse.SC_OK);
        String strResp ="OKOKOK";
        response.getWriter().println(strResp);
        
        return af;
    }
}
